<template>
  <div>
    <el-form label-width="60px" :model="account" :rules="rules" ref="formRef">
      <el-form-item label="账号" prop="username">
        <el-input v-model="account.username"></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input v-model="account.password" show-password></el-input>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { reactive, defineExpose, ref } from 'vue'
import { rules } from '../config/account-config'
import { ElForm } from 'element-plus'
import localCache from '@/utils/cache.ts'
import { useStore } from 'vuex'

const store = useStore()
const account = reactive({
  username: localCache.getCache('username') ?? '',
  password: localCache.getCache('password') ?? ''
})

const formRef = ref<InstanceType<typeof ElForm>>()
//默认情况下，只在本组件内可以使用
//外部组件使用，需要使用defineExpose主动暴露
defineExpose({
  loginAction(isKeepPassword: boolean) {
    formRef.value?.validate((isValid) => {
      if (isValid) {
        //判断是否需要记住密码
        if (isKeepPassword) {
          //本地缓存
          localCache.setCache('username', account.username)
          localCache.setCache('password', account.password)
          //发送登录请求，使用vuex的action
        } else {
          localCache.deleteCache('username')
          localCache.deleteCache('password')
        }
        store.dispatch('login/accountLoginAction', { ...account })
      } else {
        console.log('verify failed...')
      }
    })
  }
})
</script>

<style scoped></style>
